<?php defined('SYSPATH') or die('No direct script access.');

require_once(__DIR__.'/../../config/config.php');  //the GOOGLE constants

class Controller_Start extends Controller {

  private static $myuid = 1; //something like this will be handled with auth module?
  
  public function action_index() {
    
    $access_token = self::dbtoken(self::$myuid);
 
    if ($access_token) {
      $docs = self::getdocs($access_token);
      $output = self::viewdocs($docs);
    } else {
      $dest = url::kdsite('start/kdauth');
      $request = new Request($dest);
      $request->redirect($dest);
    } 
    
    $this->response->body($output);
    
  }
  
  public function action_kdauth() {
    
    $output = '<a href="'.self::authurl().'">Authorize this app</a>';
    $this->response->body($output);
    
  }
  
  //read the top doc
  public function action_top() {  
    
    $access_token = self::dbtoken(self::$myuid);
    $redirect = urlencode(url::kdsite('start/top'));
 
    if (!$access_token) {
      $output = self::link(self::authurl($redirect),'Authorize this app2');
    } else {
      $docs = self::getdocs($access_token);
      if (!isset($docs[0])) {
        
        $output = self::link(self::authurl($redirect),'Authorize this app3');
      } else {
        $content = $docs[0]->content->attributes();
        $src = $content['src'];
        $output = self::readfile($src, $access_token);
      } 
    } 
    
    $this->response->body($output);
    
  }
  
  public function action_sendtop() {  
    
    $access_token = self::dbtoken(self::$myuid);
 
    if (!$access_token) {
      url::site('start/kdauth');
    } else {
      
      $temp = APPPATH.'data/temp.txt';
      $docs = self::getdocs($access_token);
      if (!isset($docs[0])) {
        $output = self::link(self::authurl(),'Authorize this app4');
      } else {
        $content = $docs[0]->content->attributes();
        $src = $content['src'];
        $txt = self::readfile($src, $access_token);
        $fp = fopen($temp, 'w');
        fwrite($fp, $txt); 
        fclose($fp);
        
        try {
          
          //create a new instance of the 'Mailer' class
          $mailer = new Mailer(
              'webmaster@ryan.com','ryandw@gmail.com','Testing the mailer class','Hey, I am sending you a couple of fun images.'
              );
          
          //add some HTML to the message
          $mailer->addHTML('<strong>This text is formatted with HTML</strong>');
          
          //add some attachments
          $mailer->addAttachment($temp); 
          
          // send MIME email
          $mailer->send();
          
          $output = 'success';
          
        } catch(Exception $e){
          
          echo $e->getMessage();
          
          exit();
            
        }
   
        /*
        $docs = self::getdocs($access_token);  
        $content = $docs[0]->content->attributes();
        $src = $content['src'];
        $txt = self::readfile($src, $access_token);
        $attachment = new Attachment();
        $attachment->content = $txt;
        $attachment->title = $docs[0]->title;
        $attachment->to = 'ryandw@gmail.com';
        $attachment->message = 'import this.';
        $mail = $attachment->mail();
        $output = $mail ? 'success' : 'fail';
        */
      }
    }
    
    $this->response->body($output);
    
  }
  
  public function action_info() {
    $info = phpinfo();
    $this->response->body($info);
  }
  
  public function action_oauth2callback() { 
  
    if (!isset($_GET['code'])) {
      $output = 'no code';
    } else {
      
      $curl_token = self::curltoken($_GET['code']);
      $db_token = self::dbtoken(self::$myuid);
       
      if ($db_token) { 
        print 'update';
        $query = "UPDATE google_auth SET access_token = '$curl_token', updated = NOW() WHERE uid = ".self::$myuid;
      } else {
        print 'insert';
        $myuid = self::$myuid;
        $query = "INSERT INTO google_auth (uid,access_token,updated) 
                  VALUES ('$myuid','$curl_token',NOW())";
      }  
      $result = mysql_query($query);  
      if (!$result) die ('no result 2');
      
      $output = ' success';
    }
    
    $this->response->body($output);
    
    //optionally we can redirect the user
    if (isset($_GET['state'])) $this->request->redirect(url::kdsite(urldecode($_GET['state'])));  

  }
  
  
  
  // END actions ////////////////////////////////////////////
  
  //build the authurl
  public function authurl($state = NULL) {

    $base = 'https://accounts.google.com/o/oauth2/auth?';
    $url['v'] = 3;
    $url['response_type'] = 'code';
    $url['scope'] = 'https://docs.google.com/feeds'; //https://docs.google.com/feeds/documents/private/full
    if ($state) $url['state'] = $state;
    $url['redirect_uri'] = GOOGLE_REDIRECT_URI;
    $url['client_id'] = GOOGLE_CLIENT_ID;
    $url['access_type'] = 'offline';
    $authurl = $base.http_build_query($url);
    return $authurl;

  }
  
  public function curltoken($code) {
          
    $fields_string = '';
    
    //set POST variables
    $url = 'https://accounts.google.com/o/oauth2/token';
    $fields = array(
        'v' => 3,
        'code'=>urlencode($code),
        'client_id'=>urlencode(GOOGLE_CLIENT_ID),
        'client_secret'=>urlencode(GOOGLE_CLIENT_SECRET),
        'redirect_uri'=>urlencode(GOOGLE_REDIRECT_URI),
        'grant_type'=>urlencode('authorization_code'), 
      );

    //http_build_query wasn't working here
    foreach($fields as $key=>$value) { 
      $fields_string .= $key.'='.$value.'&'; 
    }
    rtrim($fields_string,'&');

    //open connection
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

    $result = curl_exec($ch);

    curl_close($ch); 
    
    $obj = json_decode($result);
    
    $access_token = $obj->access_token;  
    return $access_token;
  }
  
  //look up access token in db
  public function dbtoken($uid) {
   
    $query = "SELECT access_token FROM google_auth WHERE uid = {$uid}";
    $result = mysql_query($query);
    if (!$result) die ('no result in dbtoken');
    $num = mysql_num_rows($result);
    if (0 === $num) return false;
    if (1 === $num) return mysql_result($result,0);
    if ($num > 1) die('invalid result in dbtoken');
    
  }
  
  //really?
  public function link($url,$txt) {
    return '<a href="'.$url.'">'.$txt.'</a>';
  }
  
  //view some docs
  public function viewdocs($docs) { 

    $arr = array();
    
    foreach ($docs as $val) { 
      $title = $val->title;
      $content = $val->content->attributes();
      $src = $content['src'];
      $arr[] = '<div><a href="'.$src.'">'.$title.'</a></div>';
    }
    
    $output = implode("\r\n",$arr);
  
    return $output;
  
  }
  
  //read a file?
  public function readfile($docurl,$access_token) {
   
    $url = $docurl.'&access_token='.$access_token; //safe to assume $docurl will always end in query string?
    $str = file_get_contents($url);
    
    return $str;
    
  }
  
  //get some docs
  public function getdocs($access_token) { 
     
    $fields_string = '';
    
    //set variables
    $url = 'https://docs.google.com/feeds/default/private/full?v=3&access_token='.$access_token; 
    
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

    $result = curl_exec($ch);
    curl_close($ch);
    
    $obj = simplexml_load_string($result);

    $mydocs = $obj->entry;
    
    if (empty($mydocs)) {
      print "<p>no mydocs in getdocs</p>"; 
    }
 
    return $mydocs;
    
  }
  
}

// End Start
